package handler

import (
	"content_system/router/middleware"
	"content_system/service"
	"content_system/value"
	"content_system/value/dto"
	"github.com/gin-gonic/gin"
	"net/http"
	"sync"
)

var (
	onceContentHandler sync.Once
	contentHandler     *ContentHandler
)

func GetContentHandler() *ContentHandler {
	onceContentHandler.Do(func() {
		contentHandler = &ContentHandler{}
	})
	return contentHandler
}

type ContentHandler struct {
}

func (u *ContentHandler) Create(g *gin.Context) {
	var req dto.ContentCreateRequest
	if err := g.ShouldBindBodyWithJSON(&req); err != nil {
		g.JSON(http.StatusBadRequest, value.Fail(400, err.Error()))
		return
	}
	uid, ok := g.Get(middleware.UserID)
	if !ok {
		g.JSON(http.StatusForbidden, value.Forbidden())
		return
	}
	id, ok := uid.(int64)
	if !ok {
		g.JSON(http.StatusForbidden, value.Forbidden())
		return
	}
	resp, err := service.GetContentService().Create(g, &req, id)
	if err != nil {
		g.JSON(http.StatusInternalServerError, value.Fail(500, err.Error()))
		return
	}
	g.JSON(http.StatusOK, value.Success(resp))
	return
}

func (u *ContentHandler) Update(g *gin.Context) {
	var req dto.ContentCreateRequest
	if err := g.ShouldBindBodyWithJSON(&req); err != nil {
		g.JSON(http.StatusBadRequest, value.Fail(400, err.Error()))
		return
	}
	uid, ok := g.Get(middleware.UserID)
	if !ok {
		g.JSON(http.StatusForbidden, value.Forbidden())
		return
	}
	id, ok := uid.(int64)
	if !ok {
		g.JSON(http.StatusForbidden, value.Forbidden())
		return
	}
	resp, err := service.GetContentService().Update(g, &req, id)
	if err != nil {
		g.JSON(http.StatusInternalServerError, value.Fail(500, err.Error()))
		return
	}
	g.JSON(http.StatusOK, value.Success(resp))
	return
}

func (u *ContentHandler) Delete(g *gin.Context) {
	var req dto.ContentDeleteRequest
	if err := g.ShouldBindBodyWithJSON(&req); err != nil {
		g.JSON(http.StatusBadRequest, value.Fail(400, err.Error()))
		return
	}
	uid, ok := g.Get(middleware.UserID)
	if !ok {
		g.JSON(http.StatusForbidden, value.Forbidden())
		return
	}
	id, ok := uid.(int64)
	if !ok {
		g.JSON(http.StatusForbidden, value.Forbidden())
		return
	}
	err := service.GetContentService().Delete(g, &req, id)
	if err != nil {
		g.JSON(http.StatusInternalServerError, value.Fail(500, err.Error()))
		return
	}
	g.JSON(http.StatusOK, value.Success("sucess"))
	return
}
